/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package service.inventory.impl;

import dao.inventory.ItemHppDao;
import java.util.Date;
import java.util.List;
import java.util.Map;
import model.inventory.ItemHpp;
import model.inventory.ItemHppId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import service.inventory.ItemHppService;
import utility.NameValueList;
import utility.StringUtils;


@Service("itemHppService")
@Transactional(readOnly=true)
public class ItemHppServiceImpl implements ItemHppService {

    //void LazyInitializationException 
    String mainQuery = "select distinct hpp from ItemHpp hpp left join fetch hpp.item item "+
            "left join fetch hpp.unit unit left join fetch hpp.itemDiskons diskons ";
    
    @Autowired private ItemHppDao itemHppDao;
    
    @Transactional(readOnly=false)
    @Override
    public boolean save(ItemHpp itemHpp) {
        return itemHppDao.saveData(itemHpp);
    }

    @Override
    public boolean save(List<ItemHpp> itemHpp, Integer newSupplier, boolean isCopy) {
        return itemHppDao.saveData(itemHpp, newSupplier, isCopy);
    }
    
    @Transactional(readOnly=false)
    @Override
    public boolean delete(ItemHpp itemHpp) {
        return itemHppDao.delete(itemHpp);
    }

    @Override
    public ItemHpp get(ItemHppId id) {
        String q=mainQuery+" where hpp.id.itemId = "+id.getItemId()+
                " and hpp.id.supplierId = "+id.getSupplierId()+
                " and hpp.id.startDate = "+StringUtils.formatSqlDate(id.getStartDate());
        return itemHppDao.getByCustomQuery(q);
    }
    
    @Override
    public ItemHpp get(int itemId, Date curdate) {
        String q = mainQuery+
                ", ItemSupplier as spl where hpp.id.itemId=spl.id.itemId and hpp.id.supplierId=spl.id.supplierId and spl.aktive=true "+
                "and hpp.id.itemId = "+itemId+" and hpp.id.startDate = (select max(h2.id.startDate) "+
                    "from ItemHpp h2 where h2.id.startDate <= "+utility.StringUtils.formatSqlDate(curdate)+
                    " and h2.id.itemId=hpp.id.itemId and h2.id.supplierId=spl.id.supplierId)";
        return itemHppDao.getByCustomQuery(q);
    }

    @Override
    public List<ItemHpp> getAll(Map<NameValueList, Object> params) {
        String q = mainQuery+StringUtils.getFilter(params);
        return itemHppDao.getAll(q);
    }

    @Override
    public List<Date> getDates(int itemId, int supplierId) {
        return itemHppDao.getDates(itemId, supplierId);
    }
    
    
}
